package com.yicong.ants.manager;

import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.http.AliDns;
import com.cchao.simplelib.util.StringHelper;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.https.HttpsUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.OkHttpClient;

/**
 * 网络管理类
 */
public class HttpManager {
    /**
     * get请求
     *
     * @param url
     * @param params
     * @param callback
     */
    public static void getHttp(String url, Map<String, String> params, Callback callback) {
        OkHttpUtils
            .initClient(INSTANCE.getOkHttpClient())
            .get()
            .url(url)
            .params(params)
            .build()
            .execute(callback);
    }

    /**
     * post请求
     *
     * @param url
     * @param params
     * @param callback
     */
    public static void postHttp(String url, Map<String, String> params, Callback callback) {
        Map<String, String> map = new HashMap<>();
        if (CollectionHelper.mapContainEmpty(params)) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (StringHelper.isNotEmpty(entry.getValue())) {
                    map.put(entry.getKey(), entry.getValue());
                }
            }
            params = map;
        }

        OkHttpUtils
            .initClient(INSTANCE.getOkHttpClient())
            .post()
            .url(url)
            .params(params)
            .build()
            .execute(callback);
    }

    /**
     * 上传文件
     *
     * @param url
     * @param params
     * @param file
     * @param fileName
     * @param callback
     */
    public static void postFile(String url, Map<String, String> params, File file, String fileName, Callback callback) {
        Map<String, String> header = new HashMap<>(1);
        header.put("enctype", "multipart/form-data");
        OkHttpUtils
            .initClient(INSTANCE.getOkHttpClient())
            .post()
            .addFile("file", fileName, file)
            .url(url)
            .params(params)
            .headers(header)
            .build()
            .connTimeOut(10000)
            .readTimeOut(10000)
            .writeTimeOut(10000)
            .execute(callback);
    }

    private static class INSTANCE {
        static HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
        private static OkHttpClient okHttpClient;

        public static OkHttpClient getOkHttpClient() {
            if (okHttpClient == null) {
                okHttpClient = new OkHttpClient.Builder()
                    .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
//                    .dns(AliDns.get())
                    //其他配置
                    .build();
            }
            return okHttpClient;
        }
    }

}
